import subprocess

import img2pdf
from PyQt5.QtCore import QThread, pyqtSignal
import pandas as pd

from config import mos_attestat_print_folder


class BatchAttestatPrint(QThread):
    progress_signal = pyqtSignal(str)

    def __init__(self, filename, is_necessary_to_print_back=True, parent=None):
        QThread.__init__(self, parent)
        self.filename = filename
        self.is_necessary_to_print_back = is_necessary_to_print_back
        self.start_message, self.print_error_message, self.progress_message = '', '', ''
        self.generate_function = None
        self.folder_to_store_images = ''
        self.pdf_filename = ''

    def check_row(self, row):
        return True

    def run(self):
        self.progress_signal.emit(self.start_message)
        sheet = pd.read_excel(io=self.filename, sheet_name=0, na_filter=False, na_values='')
        subprocess.run(['mkdir', '-p', self.folder_to_store_images])
        generated_images = []
        for number, row in enumerate(sheet.values, start=1):
            self.progress_signal.emit(f'{self.progress_message} {number} из {len(sheet.values)}...')
            if not self.check_row(row):
                print(f'{self.print_error_message}: {row[:6]}')
                self.progress_signal.emit(f'{self.print_error_message}: {row}')
                continue
            for i in range(len(row)):
                row[i] = str(row[i])
            attestat_number, name, year, school, director, date, birthday, info = row[:8]
            marks = {(list(sheet.head(0))[i]): row[i] for i in range(8, len(row))}
            self.generate_function(
                name=name,
                date=date,
                attestat_number=attestat_number,
                year=year,
                school=school,
                director=director,
                birthday=birthday,
                info=info,
                is_necessary_to_print_back=self.is_necessary_to_print_back,
                marks=marks
            )
            generated_images.append(f'{mos_attestat_print_folder}/{self.folder_to_store_images}/{attestat_number}-{name}.png')
        self.progress_signal.emit('Создание PDF файла...')
        with open(self.pdf_filename, "wb") as out_file:
            out_file.write(img2pdf.convert(generated_images))
        self.progress_signal.emit('Готово.')
